# -*- coding: utf-8 -*-
"""
主窗口
"""

import os
from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QSplitter, QTabWidget, QMenuBar, QMenu, QStatusBar,
                             QFileDialog, QMessageBox, QToolBar, QLabel, QDialog)
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QAction, QIcon, QKeySequence

from .models.novel import Novel
from .services.ai_writer import AIWriter
from .services.character_generator import CharacterGenerator
from .ui.novel_editor import NovelEditor
from .ui.character_manager import CharacterManager
from .ui.ai_writer_dialog import AIWriterDialog
from .ui.settings_dialog import SettingsDialog


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.novel = Novel()
        self.ai_writer = AIWriter()
        self.character_generator = CharacterGenerator()
        
        self.init_ui()
        self.init_menu()
        self.init_toolbar()
        self.init_statusbar()
        
        # 自动保存定时器
        self.auto_save_timer = QTimer()
        self.auto_save_timer.timeout.connect(self.auto_save)
        self.auto_save_timer.start(300000)  # 5分钟自动保存一次
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("小说编写软件")
        self.setGeometry(100, 100, 1200, 800)
        
        # 创建中央widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)
        
        # 创建小说编辑器
        self.novel_editor = NovelEditor(self.novel)
        splitter.addWidget(self.novel_editor)
        
        # 创建角色管理器，传入AI写作服务
        self.character_manager = CharacterManager(self.novel, self.character_generator, self.ai_writer)
        splitter.addWidget(self.character_manager)
        
        # 设置分割器比例
        splitter.setSizes([800, 400])
        
        # 连接信号
        self.novel_editor.content_changed.connect(self.on_content_changed)
        self.character_manager.character_updated.connect(self.on_character_updated)
    
    def init_menu(self):
        """初始化菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件(&F)")
        
        new_action = QAction("新建(&N)", self)
        new_action.setShortcut(QKeySequence.New)
        new_action.triggered.connect(self.new_novel)
        file_menu.addAction(new_action)
        
        open_action = QAction("打开(&O)", self)
        open_action.setShortcut(QKeySequence.Open)
        open_action.triggered.connect(self.open_novel)
        file_menu.addAction(open_action)
        
        save_action = QAction("保存(&S)", self)
        save_action.setShortcut(QKeySequence.Save)
        save_action.triggered.connect(self.save_novel)
        file_menu.addAction(save_action)
        
        save_as_action = QAction("另存为(&A)", self)
        save_as_action.setShortcut(QKeySequence.SaveAs)
        save_as_action.triggered.connect(self.save_novel_as)
        file_menu.addAction(save_as_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出(&X)", self)
        exit_action.setShortcut(QKeySequence.Quit)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu("编辑(&E)")
        
        undo_action = QAction("撤销(&U)", self)
        undo_action.setShortcut(QKeySequence.Undo)
        undo_action.triggered.connect(self.novel_editor.undo)
        edit_menu.addAction(undo_action)
        
        redo_action = QAction("重做(&R)", self)
        redo_action.setShortcut(QKeySequence.Redo)
        redo_action.triggered.connect(self.novel_editor.redo)
        edit_menu.addAction(redo_action)
        
        # AI菜单
        ai_menu = menubar.addMenu("AI助手(&A)")
        
        ai_write_action = QAction("AI写作(&W)", self)
        ai_write_action.setShortcut("Ctrl+Shift+W")
        ai_write_action.triggered.connect(self.show_ai_writer)
        ai_menu.addAction(ai_write_action)
        
        # 工具菜单
        tools_menu = menubar.addMenu("工具(&T)")
        
        settings_action = QAction("设置(&S)", self)
        settings_action.triggered.connect(self.show_settings)
        tools_menu.addAction(settings_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助(&H)")
        
        about_action = QAction("关于(&A)", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def init_toolbar(self):
        """初始化工具栏"""
        toolbar = QToolBar("主工具栏")
        self.addToolBar(toolbar)
        
        new_action = QAction("新建", self)
        new_action.triggered.connect(self.new_novel)
        toolbar.addAction(new_action)
        
        open_action = QAction("打开", self)
        open_action.triggered.connect(self.open_novel)
        toolbar.addAction(open_action)
        
        save_action = QAction("保存", self)
        save_action.triggered.connect(self.save_novel)
        toolbar.addAction(save_action)
        
        toolbar.addSeparator()
        
        ai_write_action = QAction("AI写作", self)
        ai_write_action.triggered.connect(self.show_ai_writer)
        toolbar.addAction(ai_write_action)
    
    def init_statusbar(self):
        """初始化状态栏"""
        self.statusbar = QStatusBar()
        self.setStatusBar(self.statusbar)
        
        # 字数统计标签
        self.word_count_label = QLabel("字数: 0")
        self.statusbar.addPermanentWidget(self.word_count_label)
        
        # AI状态标签
        ai_status = "AI可用" if self.ai_writer.is_available() else "AI不可用"
        self.ai_status_label = QLabel(f"AI状态: {ai_status}")
        self.statusbar.addPermanentWidget(self.ai_status_label)
        
        self.statusbar.showMessage("就绪")
    
    def new_novel(self):
        """新建小说"""
        if self.check_save_needed():
            self.novel = Novel()
            self.novel_editor.set_novel(self.novel)
            self.character_manager.set_novel(self.novel)
            self.update_title()
            self.statusbar.showMessage("创建新小说")
    
    def open_novel(self):
        """打开小说"""
        if self.check_save_needed():
            file_path, _ = QFileDialog.getOpenFileName(
                self, "打开小说", "", "小说文件 (*.novel);;所有文件 (*)"
            )
            if file_path:
                self.novel = Novel.load_from_file(file_path)
                self.novel_editor.set_novel(self.novel)
                self.character_manager.set_novel(self.novel)
                self.update_title()
                self.statusbar.showMessage(f"打开文件: {os.path.basename(file_path)}")
    
    def save_novel(self):
        """保存小说"""
        if not self.novel.file_path:
            self.save_novel_as()
        else:
            if self.novel.save_to_file(self.novel.file_path):
                self.statusbar.showMessage("保存成功")
            else:
                QMessageBox.warning(self, "警告", "保存失败！")
    
    def save_novel_as(self):
        """另存为小说"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存小说", "", "小说文件 (*.novel);;所有文件 (*)"
        )
        if file_path:
            if self.novel.save_to_file(file_path):
                self.update_title()
                self.statusbar.showMessage(f"保存文件: {os.path.basename(file_path)}")
            else:
                QMessageBox.warning(self, "警告", "保存失败！")
    
    def auto_save(self):
        """自动保存"""
        if self.novel.file_path:
            self.novel.save_to_file(self.novel.file_path)
    
    def show_ai_writer(self):
        """显示AI写作对话框"""
        dialog = AIWriterDialog(self.novel, self.ai_writer, self)
        if dialog.exec() == QDialog.Accepted:
            content = dialog.get_generated_content()
            if content:
                self.novel_editor.insert_content(content)
    
    def show_settings(self):
        """显示设置对话框"""
        dialog = SettingsDialog(self.ai_writer, self)
        dialog.exec()
        
        # 更新AI状态
        ai_status = "AI可用" if self.ai_writer.is_available() else "AI不可用"
        self.ai_status_label.setText(f"AI状态: {ai_status}")
        
        # 更新角色管理器的AI服务
        self.character_manager.set_ai_writer(self.ai_writer)
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于", 
                         "小说编写软件 v1.0\n\n"
                         "一个功能强大的小说创作工具\n"
                         "支持章节管理、角色管理和AI写作助手")
    
    def check_save_needed(self) -> bool:
        """检查是否需要保存"""
        # 这里可以实现检查文档是否有未保存的更改
        return True
    
    def update_title(self):
        """更新窗口标题"""
        title = "小说编写软件"
        if self.novel.title:
            title += f" - {self.novel.title}"
        if self.novel.file_path:
            title += f" ({os.path.basename(self.novel.file_path)})"
        self.setWindowTitle(title)
    
    def update_word_count(self):
        """更新字数统计"""
        word_count = self.novel.get_total_word_count()
        self.word_count_label.setText(f"字数: {word_count}")
    
    def on_content_changed(self):
        """内容更改时的处理"""
        self.update_word_count()
    
    def on_character_updated(self):
        """角色更新时的处理"""
        pass
    
    def closeEvent(self, event):
        """关闭事件"""
        if self.check_save_needed():
            event.accept()
        else:
            event.ignore() 